import time
from futu import *

class StockQuoteTest(StockQuoteHandlerBase):
    def on_recv_rsp(self, rsp_pb):
        # 调用父类解析
        ret_code, data = super(StockQuoteTest, self).on_recv_rsp(rsp_pb)
        if ret_code != RET_OK:
            print("StockQuoteTest: error, msg: %s" % data)
            return RET_ERROR, data

        # 遍历每条行情，只打印指定字段
        fields = [
            'data_date', 'data_time', 'last_price', 'open_price', 'high_price', 
            'low_price', 'prev_close_price', 'volume', 'turnover', 
            'turnover_rate', 'amplitude', 'suspension', 'listing_date', 'price_spread'
        ]

        for idx, row in data.iterrows():
            print("-" * 40)
            for field in fields:
                print(f"{field}: {row.get(field, '')}")
        print("-" * 40)
        return RET_OK, data

# 初始化行情上下文
quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)

# 设置回调
handler = StockQuoteTest()
quote_ctx.set_handler(handler)

# 订阅股票实时行情
codes = ['HK.02616']  # 可以放富途特别关注的股票列表
ret, data = quote_ctx.subscribe(codes, [SubType.QUOTE])
if ret == RET_OK:
    print("订阅成功:", data)
else:
    print("订阅失败:", data)

# 持续接收推送
try:
    while True:
        time.sleep(1)  # 空循环等待推送
except KeyboardInterrupt:
    print("停止接收推送")
finally:
    quote_ctx.close()
